﻿#include "page2widget.h"
#include "cppfont.h"
#include "socket.h"

Page2Widget::Page2Widget() {
    totalPrice = 0;
}

void Page2Widget::show() {
    while (1) {
        showOrderItem();
        CppFont::clearArea(120, 400, 680, 80, 0x00ffffff);  // 清空
        showtotalPrice();
        showBtn();

        int x, y;
        //等待触摸屏 触摸
        TouchSreen touch;
        touch.waitTouch(x, y);

        // 提交订单
        if(x >= 540 && x < 620 && y >= 400 && y < 480) {
            submitOrder();
            for(int i = 0; i < (int)order.size(); i++) {
                delete order[i];
            }
            order.clear();
            totalPrice = 0;
            cout << "提交订单" << endl;
        }
        // 退出
        if(x >= 660 && x < 740 && y >= 400 && y < 480) {
            CppFont::clearArea(120, 0, 680, 480, 0x00ffffff);  // 清空
            break;
        }
    }
}

void Page2Widget::showOrderItem() {
    CppFont::clearArea(120, 0, 680, 480, 0x00ffffff);  // 清空
    CppFont::displayCharacter(150, 20, (unsigned char *)"name", 0x00000000, 1);
    CppFont::displayCharacter(400, 20, (unsigned char *)"price", 0x00000000, 1);
    CppFont::displayCharacter(600, 20, (unsigned char *)"num", 0x00000000, 1);
    cout << "order size:" << order.size() << endl;
    for(int i = 0; i < (int)order.size(); i++) {
        float price = atof(order[i]->price.c_str());
        totalPrice += 1.0 * order[i]->num * price;
        CppFont::displayCharacter(150, 60 + i * 40, (unsigned char *)order[i]->name.c_str(), 0x00000000, 1);
        CppFont::displayCharacter(400, 60 + i * 40, (unsigned char *)order[i]->price.c_str(), 0x00000000, 1);
        CppFont::displayCharacter(600, 60 + i * 40, (unsigned char *)to_string(order[i]->num).c_str(), 0x00000000, 1);
    }
}

void Page2Widget::showtotalPrice() {
    string buf = "total price:";
    string strTP = to_string(totalPrice);
    buf.append(strTP.erase(strTP.length() - 4));  // 去除末尾4个0
    CppFont::displayCharacter(120, 420, (unsigned char *)buf.c_str(), 0x00000000, 2);
}

void Page2Widget::showBtn() {
    Bmp b1;
    b1.setFileName("./res/submit.bmp");  // 提交 80*80
    b1.show(540, 400);
    b1.setFileName("./res/close_2.bmp");  // 关闭 80*80
    b1.show(660, 400);
}

void Page2Widget::submitOrder() {
    string json;
    json.append("{\"type\":3,\"sum\":\""
                + to_string(totalPrice).erase(to_string(totalPrice).length() - 4)
                + "\",\"member_id\":" + to_string(currentMember.id)
                + ",\"item\":[");
    for(int i = 0; i < (int)order.size(); i++) {
        json.append("{\"id\":" + to_string(order[i]->id)
                    + ",\"num\":" + to_string(order[i]->num) + "},");
    }
    json.erase(json.length() - 1);  // 去除末尾的 , 号
    json.append("]}");

    cout << "json:" << json << endl;
    Socket::getSocket()->sendMsg(json);
}
